package com.jzo2o.orders.manager.service.cllient;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.jzo2o.api.customer.AddressBookApi;
import com.jzo2o.api.customer.dto.response.AddressBookResDTO;
import com.jzo2o.api.market.CouponApi;
import com.jzo2o.api.market.dto.request.CouponUseReqDTO;
import com.jzo2o.api.market.dto.response.AvailableCouponsResDTO;
import com.jzo2o.api.market.dto.response.CouponUseResDTO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.Collections;
import java.util.List;

/**
 * @Author:on
 * @Description:优惠券活动客户端
 * @Date Created in 2024-08-27-12:23
 * @Modified By:
 */
@Component
@Slf4j
public class MarketClient {
    @Resource
    private CouponApi couponApi;

    //value:资源名称，sentinel基于资源进行限流，熔断
    //fallback:当getAvailable方法执行异常时会调用此方法
    //blockHandler:当发生熔断，限流走此方法
    @SentinelResource(value = "getAvailableByCouponApi", fallback = "getAvailableFallback", blockHandler = "getAvailableBlockHandler")
    public List<AvailableCouponsResDTO> getAvailable(BigDecimal totalAmount) {

        log.error("查询可用优惠券,订单金额:{}",totalAmount);
        //调用可用优惠券
        List<AvailableCouponsResDTO> available = couponApi.getAvailable(totalAmount);
        return available;
    }

    //执行异常走
    public List<AvailableCouponsResDTO> getAvailableFallback(BigDecimal totalAmount, Throwable throwable) {
        log.error("非限流、熔断等导致的异常执行的降级方法，totalAmount:{},throwable:", totalAmount, throwable);
        return Collections.emptyList();
    }

    //熔断后的降级逻辑
    public List<AvailableCouponsResDTO> getAvailableBlockHandler(BigDecimal totalAmount, BlockException blockException) {
        log.error("触发限流、熔断时执行的降级方法，totalAmount:{},blockException:", totalAmount, blockException);
        return Collections.emptyList();
    }



    @SentinelResource(value = "useByCouponApi", fallback = "useFallback", blockHandler = "useBlockHandler")
    public CouponUseResDTO use(CouponUseReqDTO couponUseReqDTO) {
        log.error("订单：{}使用优惠券：{}",couponUseReqDTO.getOrdersId(),couponUseReqDTO.getId());
        //调用可用优惠券
        CouponUseResDTO couponUseResDTO = couponApi.use(couponUseReqDTO);
        return couponUseResDTO;
    }

    //执行异常走
    public CouponUseResDTO useFallback(CouponUseReqDTO couponUseReqDTO, Throwable throwable) {
        log.error("非限流、熔断等导致的异常执行的降级方法，ordersId:{},throwable:", couponUseReqDTO.getOrdersId(), throwable);
        return couponApi.use(couponUseReqDTO);
    }

    //熔断后的降级逻辑
    public CouponUseResDTO useBlockHandler(CouponUseReqDTO couponUseReqDTO, BlockException blockException) {
        log.error("触发限流、熔断时执行的降级方法，ordersId:{},blockException:",couponUseReqDTO.getOrdersId() , blockException);
        return couponApi.use(couponUseReqDTO);
    }

}
